package com.springbootee.Service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.springbootee.Common.Rest;
import com.springbootee.Common.RestStatus;
import com.springbootee.Mapper.UserMapper;
import com.springbootee.entity.User;
import com.springbootee.uitl.JwtUtil;
import com.springbootee.uitl.MD5Util;
import jdk.nashorn.internal.parser.Token;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.UUID;



@Service
public class UserService extends ServiceImpl<UserMapper, User> {
        private   static  final Logger LOGGER= LoggerFactory.getLogger(UserService.class);
        /**
         *
         */
        @Autowired
        private  UserMapper userMapper;
        @Autowired
        private  UserService userService;
        //注册账号
        public User register(User user){
                user.setUserPassword(MD5Util.encode(user.getUserPassword()));
                synchronized (this){
                        Integer exites=userMapper.selectCount(new QueryWrapper<User>().lambda().eq(User::getUserAccount,user.getUserAccount()));
                        if (exites > 0){
                                Rest.Exception(RestStatus.BAD_REQUEST,"该账号已存在");
                        }
                        userMapper.insert(user);
                }
                return  user;
        }

        //登录账号验证
        public User login(User user){
      User exists=userMapper.selectOne(new QueryWrapper<User>().lambda().eq(User::getUserAccount,user.getUserAccount()));
        if (exists == null){
         Rest.Exception(RestStatus.BAD_REQUEST,"该账号不存在");
         return null;
        }
            if (MD5Util.check(user.getUserPassword(),exists.getUserPassword())){
            //调用token清除缓存
                exists=userService.setTokenToUser(exists, JwtUtil.encodeToken(JSONObject.toJSONString(user)));

            }else {
             LOGGER.error("token信息:",exists);
            Rest.Exception(RestStatus.BAD_REQUEST,"密码错误,请重试");

            }

          return exists;

        }


        /**
         *创建一个token的时候，清楚针对这个token的缓存
         * @param user
         * @param  token
         * @return
         */
        @CacheEvict(value = {"userinfo"},key = "#token")
        public  User setTokenToUser(User user, String token){
            user.setUserToken(token);
            userMapper.updateById(user);
            return  user;
        }


    /**
     *根据token缓存信息，可以极大降低数据库的负担并且提升速度
     * @param token
     * @return
     */
    @Cacheable(value = {"userinfo"},key = "#token")
    public  User getUserByToken(String token){
        try {
            return  userMapper.selectOne(new QueryWrapper<User>().lambda().eq(User::getUserToken,token));
        }catch (Exception e){
            return  null;
        }
    }
}
